package nku.csc660;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client
{
	private Socket MyClient = null;
	private boolean connection = false;
	private DataInputStream inputStream = null;
    private BufferedReader input = null;
    private PrintWriter output = null;

	public Client()
	{
		try
		{
			startConnection();
		}
		catch(IOException e)
		{
			System.out.println("No streams opened for input and output!");
		}

		if(this.isConnected())
		{
			try
			{
				openInputStream();
				openOutputStream();
			}
			catch(IOException e)
			{
				System.out.println("IOException was thrown when trying to open input and output streams!");
				connection = false;
			}
		}
	}

	private void startConnection() throws IOException
	{
		while(!connection)
		{
			try
			{
				MyClient = new Socket("localhost", 9999);
				connection = true;
				System.out.println("Conneted to Server!");
			}
			catch(IOException e)
			{
				System.out.println(e);
				System.out.println("Connection to Server Failed!");
				throw new IOException("Connection to Server Failed");
			}
		}
	}

	private void openInputStream()throws IOException
	{
		try
		{
			inputStream = new DataInputStream(MyClient.getInputStream());
			input = new BufferedReader(new InputStreamReader(inputStream));
			System.out.println("The input stream is opened to recieve messages from Server!");
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Failed to open an input stream to recieve messages from Server!");
			throw new IOException("Failed to open an input stream to recieve messages from Server!");
		}
	}

	private void openOutputStream()throws IOException
	{
		try
		{
			output = new PrintWriter(MyClient.getOutputStream());
			System.out.println("The output stream is opened to send messages to Server!");
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Failed to open stream to send messages to Server!");
			throw new IOException("Failed to open stream to send messages to Server!");
		}
	}

    public void sendMessage(String line)
    {
    	output.println(line);
    	output.flush();
    }

    public String readLine()throws IOException
    {
    	String line = null;
    	try
    	{
    		line = input.readLine();
		}
		catch(IOException e)
		{
			System.out.println(e);
			System.out.println("Communication Failed!");
			throw new IOException("Communication Failed, Couldn't readLine!");
		}
		return line;
    }

    public boolean isConnected()
    {
    	return connection;
    }

    public void cleanUp()
    {
    	this.output.flush();
    	this.MyClient = null;
		this.inputStream = null;
	    this.input = null;
	    this.output = null;
    }
}
